/*   
 * Copyright (c) 2011, TUgether, TU Braunschweig
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
 /**
 * @author Mohamed Karray <mohamed.karray@gmx.de>
 *
 */
 

package de.tu_bs.tugether.liferayunit.liferayPages.controlPanel;

import java.io.IOException;

import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.javascript.host.Event;

public class EditRolePermissionPage {
	HtmlPage page ;

	public EditRolePermissionPage(HtmlPage page) {
		super();
		this.page = page;
	}

	public void removePersmissionFromRole(String role, String permission) throws IOException{
		this.deployPersmissionToRole(role, permission, false);
	}
	public void assignPersmissionToRole(String role, String permission) throws IOException{
		this.deployPersmissionToRole(role, permission, true);
	}
	
	private void deployPersmissionToRole(String role, String permission, boolean check) throws IOException{
		String headerPermissionId = this.getHeaderIdOfRole(permission);
		String xPath = "//self::node()[normalize-space(text())='"+role+"']/ancestor-or-self::tr[1]/descendant::td[@headers='"+headerPermissionId+"']/descendant::input[@type='checkbox']";
		HtmlCheckBoxInput checkBox = page.getFirstByXPath(xPath);
		checkBox.setChecked(check);
		HtmlSubmitInput submit = page.getFirstByXPath("//input[@type='submit']");
		final Event event = new Event(submit, Event.TYPE_SUBMIT);
		submit.click(event);
	}
	
	private String getHeaderIdOfRole(String permission){
		HtmlElement el = page.getFirstByXPath("//th[normalize-space(text())='"+permission+"']");
		return el.getId();
	}
	
	public HtmlPage getPage() {
		return page;
	}

	
}
